<?php
// 接口-生产统计
namespace interface\v1;

use verify;

class machiningStatisticsClass extends index
{
	private const page    = 'machiningInOrder';
	private const table   = 'machining_in_order';
	private const tableMx = 'machining_in_order_detail';
	
	
	function dataBoard()
	{
		/**
		 * 金额单位格式化
		 *
		 * @param $money
		 * @return string
		 */
		function moneyUnit($money): string
		{
			return $money > 10000 ? round(($money / 10000), 2) . '万' : round($money, 2);
		}
		
		$this->code = 1;
		$date       = $this->post('date');
		//采购金额
		$where = " and coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'recordDate');
		}
		// $purchaseMoney = find(array('table' => 'purchase_order', 'where' => "state = '已确认'" . $where, 'sum' => "money"));
		//
		// //付款金额
		// if ($date) {
		// 	$where .= $this->timeComparison($date, 'date', 'b.recordDate');
		// }
		// $paymentAmount = (float)find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.classify = 0  " . $where, 'sum' => "money"));
		// //核销单
		// $paymentAmount += (float)find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.type = '预付冲应付' " . $where, 'sum' => "money"));
		// $where         = '';
		// //来料质检合格率
		// $qRate = static::qualityOrderRate($date);
		// //按期交货率
		// $where                = ''; //recordDate
		// $orderNum             = find([
		// 	'table'  => "purchase_order",
		// 	'field'  => "IFNULL(count(id),0) as num",
		// 	'single' => " coid = '" . self::$coid . "' state = '已确认' " . $where,
		// ])['num'] ?? 0;
		// $onScheduleNum        = find([
		// 	'table'  => "purchase_order",
		// 	'field'  => "IFNULL(count(id),0) as num",
		// 	'single' => " coid = '" . self::$coid . "' state = '已确认' and actual_delivery_date is not null and deliveryDate >= actual_delivery_date " . $where,
		// ])['num'] ?? 0;
		// $scheduleDeliveryRate = ($orderNum > 0 ? round(($onScheduleNum / $orderNum) * 100, 1) : 0);
		
		$this->resp['data'] = [
			[
				'type'  => '产值',
				'money' => moneyUnit($purchaseMoney),
			],
			[
				'type'  => '材料',
				'money' => moneyUnit($paymentAmount),
			],
			[
				'type'  => '人工',
				'money' => $scheduleDeliveryRate > 0 ? $scheduleDeliveryRate . '%' : $scheduleDeliveryRate,
			],
			[
				'type'  => '分摊费用',
				'money' => $qRate > 0 ? $qRate . '%' : $qRate,
			],
			[
				'type'  => '按期交货率',
				'money' => $qRate > 0 ? $qRate . '%' : $qRate,
			],
		];
	}
	
	function outputStat()
	{
		$this->code = 1;
		$series     = [
			'name'   => '产值',
			'type'   => 'line',
			'smooth' => true,
		];
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$data       = [];
		foreach ($months as $month) {
			$num    = 0;
			$result = find([
				'table' => self::table . ' as m, ' . self::tableMx . ' as d',
				'field' => 'd.materialSkuId, d.num, d.unit',
				'where' => " m.id = d.orderId AND date_format(`recordDate`, '%Y-%m') = '$month' AND "
				           . generateWhere([
						'd.coid'  => self::$coid,
						'm.state' => '已确认',
					]),
			]);
			foreach ($result['array'] as $item) {
				$num += inventoryBalanceClass::toMainUnit($item['materialSkuId'], $item['num'], $item['unit']);
			}
			$data[] = $num;
		}
		$series['data']     = $data;
		$this->resp['data'] = [
			'title'  => ['产值'],
			"data"   => $months,
			"series" => [$series],
		];
	}
	
	/**
	 * 计时计件工资
	 *
	 * @return void
	 */
	function hourlyIeceRate()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res        = [];
		foreach ($months as $m) {
			$res[] = [
				'onScheduleNum' => inventoryDefaultClass::deliveryRate('按期交货订单笔数', $m),
				'delayNum'      => inventoryDefaultClass::deliveryRate('延期交货订单笔数', $m),
			];
		}


// 		$people_fee_tip = componentClass::tipComponent('人工=计时工资+计件工资','?');
// 		$date = $this->post('date');
// 		$where = " and a.coid = '".self::$coid."' and a.state = '已确认' ";
// 		if ($date) {
// 			$where .= self::timeComparison($date, field: 'a.recordDate');
// 		}
// 		$outputValue = 0; //产值
// 		$materialFee = 0; //材料
// 		$peopleFee = 0; //人工
// 		$costSharing = 0; //分摊费用
// 		$costCountClass = new costCountClass();
// 		$result = find(array("table"=>"machining_order as a join machining_order_mx as mx on a.id = mx.orderId","field"=>"a.*,mx.id as mxId,mx.materialId","where"=>" 1 ".$where." order by a.recordDate desc,a.time desc"));
// 		if(is_array($result['array'])){
// 			foreach ($result['array'] as $array){
// 				$material = query("material"," id = '$array[materialId]' ","salePrice");
// 				$result = $costCountClass->inFee($array['mxId']);
// 				$peopleFee += $costCountClass->peopleFee($array['mxId']);
// 				$materialFee += $costCountClass->materialFee($array['mxId']);
// 				$outputValue += $result['num']*$material['salePrice'];
// 				$costSharing += $result['money'];
// 			}
// 		}
// 		$json['html'] = '';
// 		//产值
// 		$text = $outputValue > 10000 ? '万' : '';
// 		$money = round($outputValue > 10000 ? ($outputValue / 10000) : $outputValue, 2);
// 		$json['html'] .= <<<efo
//                         <li class="quarter left vertical-line">
//                             <div class="title-card-li-content">
//                                <div>产值{$output_value_tip}</div>
//                                 <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
//                             </div>
//                         </li>
//
// efo;
// 		//材料
// 		$text = $materialFee > 10000 ? '万' : '';
// 		$money = $materialFee > 10000 ? round(($materialFee / 10000), 2) : round($materialFee, 2);
// 		$json['html'] .= <<<efo
//                         <li class="quarter left vertical-line">
//                             <div class="title-card-li-content">
//                                 <div>材料{$material_fee_tip}</div>
//                                 <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
//                             </div>
//                         </li>
//
// efo;
// 		//人工
// 		$text = $peopleFee > 10000 ? '万' : '';
// 		$money = round($peopleFee > 10000 ? ($peopleFee / 10000) : $peopleFee, 2);
// 		$json['html'] .= <<<efo
//                         <li class="quarter left vertical-line">
//                             <div class="title-card-li-content">
//                                <div>人工{$people_fee_tip}</div>
//                                 <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
//                             </div>
//                         </li>
//
// efo;
// 		//分摊费用
// 		$text = $costSharing > 10000 ? '万' : '';
// 		$money = round($costSharing > 10000 ? ($costSharing / 10000) : $costSharing, 2);
// 		$json['html'] .= <<<efo
//                         <li class="quarter left vertical-line">
//                             <div class="title-card-li-content">
//                                 <div>分摊费用</div>
//                                 <div><span class="title-card-li-money">{$money}</span><span>{$text}</span></div>
//                             </div>
//                         </li>
//
// efo;
		$this->resp['data'] = [
			'title'     => ['按期交货订单笔数', '延期交货订单笔数'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '按期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'onScheduleNum'),
				],
				[
					'name'   => '延期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'delayNum'),
				],
			],
		];
	}
	
	/**
	 * 生产计划按期完成率
	 *
	 * @return void
	 */
	function completionRate()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res        = [];
		foreach ($months as $m) {
			$res[] = [
				'onScheduleNum' => inventoryDefaultClass::deliveryRate('按期交货订单笔数', $m),
				'delayNum'      => inventoryDefaultClass::deliveryRate('延期交货订单笔数', $m),
			];
		}
		$this->resp['data'] = [
			'title'     => ['按期交货订单笔数', '延期交货订单笔数'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '按期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'onScheduleNum'),
				],
				[
					'name'   => '延期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'delayNum'),
				],
			],
		];
	}
	
	/**
	 * 物耗
	 *
	 * @return void
	 */
	function material()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$items      = ['标准物耗', '实际物耗'];
		$series     = [];
		foreach ($items as $item) {
			$data = [];
			foreach ($months as $month) {
				if ($item == '标准物耗') {
					$total  = 0;
					$result = find([
						'table' => 'machining_order_detail as d, machining_order as m',
						'field' => 'd.materialSkuId, d.quantity as num, d.unit',
						'where' => " m.id = d.orderId AND date_format(m.time, '%Y-%m') = '$month' AND "
						           . generateWhere([
								'd.coid'  => self::$coid,
								'm.state' => '已确认',
							]),
					]);
					foreach ($result['array'] as $array) {
						$total += inventoryBalanceClass::toMainUnit($array['materialSkuId'], $array['num'], $array['unit']);
					}
					$data[] = $total;
					continue;
				} else {
					// 领料
					$pickNum      = 0;
					$pickOrderAll = find([
						'table' => 'pick_order as m join pick_order_detail as d on m.id = d.orderId',
						'field' => 'd.materialSkuId, d.num, d.unit ',
						'where' => " m.id = d.orderId AND date_format(m.recordDate, '%Y-%m') = '$month' AND "
						           . generateWhere([
								'd.coid'  => self::$coid,
								'm.type'  => 0,
								'm.state' => '已确认',
							]),
					]);
					foreach ($pickOrderAll['array'] as $array) {
						$pickNum += inventoryBalanceClass::toMainUnit($array['materialSkuId'], $array['num'], $array['unit']);
					}
					$pickNum = round($pickNum, 2);
					
					//退料
					$refundNum      = 0;
					$refundOrderAll = find([
						'table' => 'pick_order as m join pick_order_detail as d on m.id = d.orderId',
						'field' => 'd.materialSkuId, d.num, d.unit ',
						'where' => " m.id = d.orderId AND date_format(m.recordDate, '%Y-%m') = '$month' AND "
						           . generateWhere([
								'd.coid'  => self::$coid,
								'm.type'  => 1,
								'm.state' => '已确认',
							]),
					]);
					foreach ($refundOrderAll['array'] as $array) {
						$refundNum += inventoryBalanceClass::toMainUnit($array['materialSkuId'], $array['num'], $array['unit']);
					}
					$total = round($pickNum - $refundNum, 2);
				}
				$data[] = $total;
			}
			$series[] = [
				"name"   => $item,
				"type"   => "line",
				"smooth" => 1,
				"data"   => $data,
			];
		}
		$this->resp['data'] = [
			'title'  => $items,
			"data"   => $months,
			"series" => $series,
		];
	}
}
